package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.dto.SetmealDto;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.entity.Setmeal;
import com.example.reggie.entity.SetmealDish;
import com.example.reggie.mapper.SetmealMapper;
import com.example.reggie.service.SetmealDishService;
import com.example.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐，同时保存套餐菜品数据
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息到套餐表setmeal
        this.save(setmealDto);

        Long dishId = setmealDto.getId();

        //套餐菜品
        List<SetmealDish> setmealDishes=setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish:setmealDishes
        ) {
            setmealDish.setSetmealId(dishId);
        }


        //保存菜品数据到菜品表setmeal_dish
        setmealDishService.saveBatch(setmealDishes);

        //清理redis缓存
        String key="setmeal_"+setmealDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        //dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    /**
     * 根据id删除套餐信息
     * @param ids
     */
    @Transactional
    @Override
    public void delete(Long ids) {
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,ids);

        Setmeal setmeal = this.getById(ids);

        //清理redis缓存
        String key="setmeal_"+setmeal.getCategoryId()+"_1";
        redisTemplate.delete(key);

        setmealDishService.remove(dishLambdaQueryWrapper);
        this.removeById(ids);
    }
}
